package objects.parsers;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.htmlcleaner.ConfigFileTagProvider;
import org.htmlcleaner.HtmlCleaner;

import org.htmlcleaner.TagNode;

import objects.Release;


public class RSSParser {
	
	private HtmlCleaner _HTC;
	
	private List<Release> _RELEASES;
	
	/**
	 * List holding the source for the release fields
	 * 		Holds fields in this format:
	 * 		- namefield
	 * 		- downloadlink
	 * 		
	 */
	private String[] _ARGS;
	
	public void parseARGS(String Subunit){
		TagNode SettingsNode = null;
		try {
			SettingsNode = _HTC.clean
			(new File("./botSRC/tagconfigs/RSSconf.xml")).findElementByName(Subunit, true);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		}
		TagNode[] ValuesNode = SettingsNode.getAllElements(false);
		_ARGS = new String[ValuesNode.length];

		for(int i = 0; i < ValuesNode.length;i++){
			_ARGS[i] = ValuesNode[i].getText().toString();
		}
		
	}
	
	public RSSParser(){
		_RELEASES = new ArrayList<Release>();
		
		_HTC = new HtmlCleaner
			(new ConfigFileTagProvider(new File("./botSRC/tagconfigs/nullparse.xml")));
		
	}
	
	

	/**
	 * @param Page
	 * @param confName
	 * @return
	 * 
	 * Combs through the page and pulls releases from the 'item' nodes within the master
	 * 'channel' node.
	 * 
	 */
	public List<Release> Parse(String Page, String confName){
		this.parseARGS(confName);
		
		TagNode chNODE = null;
		try {
			chNODE = _HTC.clean(Page).findElementByName("channel", true);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
		TagNode[] rlsITEMS = chNODE.getElementsByName("item", true);
		
		for (TagNode tagNode : rlsITEMS) {
			System.out.println(tagNode.getText().toString());
		}	
		return _RELEASES;
	}
	public List<Release> Parse(File FPage, String confName){
		this.parseARGS(confName);
		
		TagNode chNODE = null;
		try {
			chNODE = _HTC.clean(FPage).findElementByName("channel", true);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
		TagNode[] Items = chNODE.getElementsByName("item", true);
		
		for (TagNode tagNode : Items) {
			System.out.println("New Release Created With Name: " + 
					tagNode.findElementByName(_ARGS[0], false).getText().toString());
			
			_RELEASES.add(new Release
					(tagNode.findElementByName(_ARGS[0], false).getText().toString()
					,tagNode.findElementByName(_ARGS[1], false).getText().toString()));
		}
		return _RELEASES;
	}
	
	
	
	public String[] getARGS(){
		return _ARGS;
	}
	
	

}
